<template>
    <el-card>
     <el-tabs v-model="activeProcessId" type="card">
        <!-- 第一层选项 -->
      <el-tab-pane
        v-for="workflow in workflowProcessBuProductList"
        :key="workflow.id"
        :label="workflow.workflowName"
        :name="workflow.id"
      >
<!-- 第二层选项 -->
        <div v-if="workflow.process && workflow.process.length>0">
            <el-button-group>
            <el-button
            v-for="process in workflow.process"
            :key="process.id"
            :label="process.processName"
            :name="process.id"
            @click="activeStepId = process.id" style="border: none;">
            {{ process.processName }}
        </el-button>
        </el-button-group>
        </div>


        <div>
        <el-button label="新增" @click="isShowAddWindow">新增</el-button>
        <el-button label="修改" @click="editWindow">编辑</el-button>
        <el-button label="删除" @click="deleteWindow">删除</el-button>
        <el-table :data="taskList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />

            <el-table-column label="任务编号" prop="taskCode"/>
            <el-table-column label="任务名称" prop="taskName"/>
            <el-table-column label="工作站编号" prop="workstationCode"/>
            <el-table-column label="工作站名称" prop="workstationName"/>
            <el-table-column label="排产数量" prop="scheduledQuantity"/>
            <el-table-column label="已生产数量" prop="producedQuantity"/>
            <el-table-column label="开始生产时间" prop="startTime"/>
            <el-table-column label="生产时长（分钟）" prop="productionDuration"/>
            <el-table-column label="预计完成时间" prop="estimatedCompletionTime"/>
            <el-table-column label="显示颜色" prop="displayColor">
                <template v-slot="scope">
                    <el-color-picker v-model="scope.row.displayColor" disabled />
                </template>
            </el-table-column>
        </el-table>
         <!-- 分页组件pagination -->
            <el-pagination
      v-if="pagination.total > 0"
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 50]"
      layout="total, sizes, prev, pager, next"
      :total="pagination.total"
      @size-change="fetchTaskList"
      @current-change="fetchTaskList"
      style="margin-top: 15px; justify-content: flex-end;"
    />
        </div>
        </el-tab-pane>
        </el-tabs>
    </el-card>

<!-- 新增窗口 -->
    <el-dialog
    :title="dialogTitle"
    v-model="isAdd"
    width="80%"
    :close-on-click-modal="false">
    <el-form :model="taskListForm" label-width="100px">
        <el-row :gutter="20">
            <el-col :span="12">
                <el-form-item label="任务编号" required>
                    <el-input v-model="taskListForm.taskCode" placeholder="任务编号"/>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="任务名称">
                    <el-input v-model="taskListForm.taskName" placeholder="任务名称"/>
                </el-form-item>
            </el-col>
        </el-row>

        <el-row :gutter="20">
            <el-col :span="12">
                <el-form-item label="工作站编号" >
                    <el-input v-model="taskListForm.workstationCode" placeholder="工作站编号" disabled>
                        <template #append>
                    <el-button :icon="Search" @click="showWorkflowDialog" />
                </template>
                    </el-input>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="工作站名称">
                    <el-input v-model="taskListForm.workstationName" placeholder="工作站名称" disabled/>
                </el-form-item>
            </el-col>
        </el-row>

        <el-row :gutter="20">
            <el-col :span="12">
                <el-form-item label="排产数量">
                    <el-input-number v-model="taskListForm.scheduledQuantity" :min="0" style="width: 100%;" placeholder="排产数量"/>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="已生产数量">
                    <el-input-number v-model="taskListForm.producedQuantity" :min="0" style="width: 100%;" placeholder="已生产数量"/>
                </el-form-item>
            </el-col>
        </el-row>

        <el-row :gutter="20">
            <el-col :span="12">
                <el-form-item label="开始生产时间">
                    <el-date-picker
                        v-model="taskListForm.startTime"
                        type="datetime"
                        placeholder="选择开始时间"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        style="width: 100%;"
                    />
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="生产时长（分钟）">
                    <el-input-number v-model="taskListForm.productionDuration" :min="0" style="width: 100%;" placeholder="生产时长（分钟）"/>
                </el-form-item>
            </el-col>
        </el-row>

        <el-row :gutter="20">
            <el-col :span="12">
                <el-form-item label="预计完成时间">
                    <el-date-picker
                        v-model="taskListForm.estimatedCompletionTime"
                        type="datetime"
                        placeholder="选择预计完成时间"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        style="width: 100%;"
                    />
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="显示颜色">
                    <el-color-picker v-model="taskListForm.displayColor" show-alpha />
                </el-form-item>
            </el-col>
        </el-row>

        <el-form-item>
            <div style="width: 100%; text-align: center; margin-top: 20px;">
                <el-button @click="isAdd = false">取消</el-button>
                <el-button type="primary" @click="submitTaskListForm">提交</el-button>
            </div>
        </el-form-item>

    </el-form>
    
    </el-dialog>

<!-- 编辑窗口 -->
     <el-dialog
    title="编辑任务"
    v-model="isEdit"
    width="80%"
    :close-on-click-modal="false">
    <el-form :model="editForm" label-width="100px">
        <el-row :gutter="20">
            <el-col :span="12">
                <el-form-item label="任务编号" required>
                    <el-input v-model="editForm.taskCode" placeholder="任务编号"/>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="任务名称">
                    <el-input v-model="editForm.taskName" placeholder="任务名称"/>
                </el-form-item>
            </el-col>
        </el-row>

        <el-row :gutter="20">
            <el-col :span="12">
                <el-form-item label="工作站编号" >
                    <el-input v-model="editForm.workstationCode" placeholder="工作站编号" disabled>
                        <template #append>
                    <el-button :icon="Search" @click="showWorkflowDialog" />
                </template>
                    </el-input>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="工作站名称">
                    <el-input v-model="editForm.workstationName" placeholder="工作站名称" disabled/>
                </el-form-item>
            </el-col>
        </el-row>

        <el-row :gutter="20">
            <el-col :span="12">
                <el-form-item label="排产数量">
                    <el-input-number v-model="editForm.scheduledQuantity" :min="0" style="width: 100%;" placeholder="排产数量"/>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="已生产数量">
                    <el-input-number v-model="editForm.producedQuantity" :min="0" style="width: 100%;" placeholder="已生产数量"/>
                </el-form-item>
            </el-col>
        </el-row>

        <el-row :gutter="20">
            <el-col :span="12">
                <el-form-item label="开始生产时间">
                    <el-date-picker
                        v-model="editForm.startTime"
                        type="datetime"
                        placeholder="选择开始时间"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        style="width: 100%;"
                    />
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="生产时长（分钟）">
                    <el-input-number v-model="editForm.productionDuration" :min="0" style="width: 100%;" placeholder="生产时长（分钟）"/>
                </el-form-item>
            </el-col>
        </el-row>

        <el-row :gutter="20">
            <el-col :span="12">
                <el-form-item label="预计完成时间">
                    <el-date-picker
                        v-model="editForm.estimatedCompletionTime"
                        type="datetime"
                        placeholder="选择预计完成时间"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        style="width: 100%;"
                    />
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="显示颜色">
                    <el-color-picker v-model="editForm.displayColor" show-alpha />
                </el-form-item>
            </el-col>
        </el-row>

        <el-form-item>
            <div style="width: 100%; text-align: center; margin-top: 20px;">
                <el-button @click="isAdd = false">取消</el-button>
                <el-button type="primary" @click="submitTaskListForm">提交</el-button>
            </div>
        </el-form-item>

    </el-form>
    
    </el-dialog>

    <!-- 选择工作台 -->
    <el-dialog v-model="isWorkflowShow"
        title='选择工作站'
        :close-on-click-modal="false"
        >
        <el-table :data="workflowList" @row-click="handleWorkflowSelect">
            <el-table-column label="工作台编码" prop="workflowCode"/> 
            <el-table-column label="工作台名称" prop="workflowName"/> 
            <el-table-column label="状态" prop="status">
                <template #default="scope">
                    <!-- scop.row代表当前一行 -->
                    {{scope.row.status ==  1?'启用':'禁用'}}
                </template>
            </el-table-column>
            <el-table-column label="描述" prop="workflowDescription"/> 
            <el-table-column label="备注" prop="remarks"/> 
        </el-table>
    </el-dialog>


</template>

<script setup>
import { ref, reactive, watch } from 'vue';
import { Plus, Search, Refresh, Edit, Delete, MessageBox, Check } from '@element-plus/icons-vue'
import { 
    ElButton, 
    ElMessage, 
    ElMessageBox,
    ElDialog,          // 确保 ElDialog 也有导入
    ElForm, ElFormItem, // 确保 ElForm 和 ElFormItem 也有导入
    ElInput, 
    ElInputNumber,     // 【新增】数字输入框
    ElDatePicker,      // 【新增】日期时间选择器
    ElColorPicker,     // 【新增】颜色选择器
    ElSelect, ElOption // 如果你用到了下拉选择
} from "element-plus";
// API函数：从我们自己写的 api 文件中，导入所有和后端交互的函数
import { getTaskList,addTaskList, updateTaskList, deleteTaskList, batchDeleteTaskList } from '@/api/taskList';
import { getWorkflowProcessByProduct } from "@/api/workflow";
import { getWorkflowPage } from '@/api/workflow';
// 接受从前一个页面传来的数据
const props = defineProps({
    materialId:{
        type: [Number,String],
            required: true
    },
    productionOrderId:{
       type: [Number,String],
            required: true
    }
})

// 定义一个分页的数据
const pagination = ref({currentPage:1,pageSize:10,total:0})

// 获取查到的所有数据
const workflowProcessBuProductList = ref([]);//存放
const taskList = ref([]);//任务数据
const workflowList = ref([]);

//存储当前是哪一个标签页（第一层）
const activeProcessId = ref(null);
const activeWorkflowId = ref(null);//哪一个工作站

//存储当前是哪一个标签页中的标签选项（第二层）
const activeStepId =ref(null);

//一个process流程的id，默认为0，直接查所有
const defaultValue = ref(null);


//新增窗口控制显示的函数
const isAdd = ref(false)
const isWorkflowShow = ref(false);
const isEdit =ref(false);

//窗口的名字
const dialogTitle = ref(null);



//新增和编辑的内容表单
const getTaskListForm =()=>({
    id:null,taskCode: "",taskName:"",productionOrderId:"",
    productionOrderCode:"",processId:null,workflowId:null,workstationCode:"",
    workstationName:"",scheduledQuantity:null,producedQuantity:null,
    startTime:"",productionDuration:null,estimatedCompletionTime:"",
    displayColor:"",createTime:"",updateTime:""
});

//workflow的内容表单
const getWorkflowList=()=>({
    id:null,workflowCode:"",workflowName:"",
    status:null,workflowDescription:"",remarks:"",
    createTime:"",createBy:"",updateTime:"",
    updateBy:"",deleteFlag:""
})

//用来存储窗口Form中的信息
const taskListForm = ref(getTaskListForm());
const workflowFrom = ref(getWorkflowList());
const selectedTasks = ref([]); //存储选择的信息
const editForm = ref(getTaskListForm()); 
const deleteForm = ref(getTaskListForm());//存储要删除的信息
// -----------------------------------
const handleSearch = (data)=>{

    getWorkflowProcessByProduct(
        defaultValue.value,
        props.materialId,
    ).then(res=>{
        workflowProcessBuProductList.value= res.data.list;
    });
    
}
//提交表单
const submitTaskListForm=()=>{
    
    if (isAdd.value) { 
        taskList.value.processId = activeProcessId.value;
        const payload = {...taskListForm.value};
        // 调用新增接口
        addTaskList(payload).then(res => {
            // 在 .then() 中处理成功后的逻辑
            ElMessage.success('新增成功！'); // 1. 弹出成功提示
            isAdd.value = false;           // 2. 关闭弹窗
            fetchTaskList();               // 3. 刷新背景表格数据
        }).catch(err => {
            // 在 .catch() 中处理失败的逻辑
            console.error("新增任务失败:", err);
            ElMessage.error('新增失败，请稍后再试！');
        });
    } else {
        const payload = {...editForm.value}
        // 这里是未来用于处理编辑逻辑的地方
        updateTaskList(payload).then(res=>{
            ElMessage.success('修改成功');
            isEdit.value = false;
            fetchTaskList(); // 3. 刷新背景表格数据
        })
    }
}
//删除
const handelDelete =()=>{
    deleteTaskList(deleteForm.value.id).then(res=>{
        ElMessage.success("删除成功");
        fetchTaskList();//重新查询
    })
}
//批量删除
const handelbatchDelete=()=>{
    const idsToDelete = selectedTasks.value.map(task=>task.id);
    batchDeleteTaskList(idsToDelete).then(res=>{
        ElMessage.success('删除成功');
        fetchTaskList();
    })
}
//查询tasklist信息
const fetchTaskList = ()=>{
    getTaskList(
        pagination.value.currentPage,
        pagination.value.pageSize,
        props.productionOrderId,
        activeStepId.value,
        activeWorkflowId.value
    ).then(res=>{
        taskList.value= res.data.list;
        pagination.value.total = res.data.total;
    })
}
// ---------------------
const showWorkflowDialog=()=>{
    isWorkflowShow.value =true;
    SearchWorkflow();
}
// 查询工作台
const SearchWorkflow=()=>{
    getWorkflowPage(
        1,
        10,
        workflowFrom.value
    ).then(res=>{
        workflowList.value = res.data.list;
        pagination.value.total = res.data.total;
    })
}
//选择工作台
const handleWorkflowSelect =(selectedRow)=>{
    if(selectedRow){
    taskListForm.value.workflowId = selectedRow.id;
    taskListForm.value.workstationCode = selectedRow.workflowCode;
    taskListForm.value.workstationName = selectedRow.workflowName;    
}
    if(isEdit){
        editForm.value.workflowId = selectedRow.id;
        editForm.value.workstationCode = selectedRow.workflowCode;
        editForm.value.workstationName = selectedRow.workflowName;
    }
}



//新增的控制函数
const isShowAddWindow = ()=>{
    taskListForm.value = null;
    dialogTitle.value = '新增任务';
    const newForm = getTaskListForm(); 
    newForm.productionOrderId = props.productionOrderId;
    newForm.processId = activeStepId.value;
    taskListForm.value = newForm;
    isAdd.value = true;
}
//编辑的控制函数
const editWindow =()=>{
    // 1. 检查选中项的数量是否为 1
    if (selectedTasks.value.length !== 1) {
        ElMessage.warning('请选择一项进行编辑！');
        return;
    }

    // 2. 从数组中取出唯一被选中的对象
    const selectedItem = selectedTasks.value[0];

    // 3. 将选中对象的数据，“拷贝”到我们专门用于编辑的 editForm 中
    editForm.value = { ...selectedItem };

    // 4. 【核心】在这里，我们手动把当前激活的 workflowId 补充进去！
    editForm.value.workflowId = activeWorkflowId.value;

    // 5. 打开弹窗
    isEdit.value = true;
}
// 多选框框
const handleSelectionChange = (selection)=>{
   selectedTasks.value = selection;
}
//删除窗口
const deleteWindow =()=>{
    if(selectedTasks.value.length === 0){
        ElMessage.warning('请选择要删除的选项')
    }
    if(selectedTasks.value.length === 1){
        // 调用删除一个
        const selectedItem = selectedTasks.value[0];
        deleteForm.value = {...selectedItem};
        handelDelete();
    }
    if(selectedTasks.value.length > 1){
        handelbatchDelete();
    }
}

//--------------------------------------------
//使用watch出发第一次数据加载，并响应id变化
watch(()=>props.materialId,(newId)=>{
    if(newId){
        handleSearch();
    }
},{
    immediate: true
}
);

watch(() => activeStepId.value, (newValue, oldValue) => {
    if (newValue) {
        pagination.value.currentPage = 1;
        fetchTaskList();
    }
});
// 【新增】：监听 activeProcessId (用户切换Tab时) 的变化
watch(activeProcessId, (newId) => {
    // 1. 根据新 Tab 的 id (newId)，从列表中找到对应的 workflow 对象
    const currentWorkflow = workflowProcessBuProductList.value.find(w => w.id === newId);

    if (currentWorkflow) {
        // 2. 从找到的 workflow 对象中，更新 activeWorkflowId
        //    根据我们上次确认的数据结构，工作流ID就是对象本身的 id
        activeWorkflowId.value = currentWorkflow.id;

        // 3. 同时，更新第二层选项的默认选中项（工序）
        if (currentWorkflow.process && currentWorkflow.process.length > 0) {
            // 默认选中新 Tab 下的第一个工序
            activeStepId.value = currentWorkflow.process[0].id;
        } else {
            // 如果新 Tab 下没有工序，则清空
            activeStepId.value = null;
            taskList.value = []; // 同时清空表格数据
        }
    }
});



</script>

<style scoped>
</style>